package com.xiaozhen.tcp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.xiaozhen.tcp.server.TcpServer;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.yaml.snakeyaml.Yaml;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/14 9:07
 * @description:
 */
@SpringBootApplication(scanBasePackages = {"com.xiaozhen"})
@MapperScan(basePackages = {"com.xiaozhen.*.dao"})
@EnableDiscoveryClient
@Slf4j
public class TcpServerApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(TcpServerApplication.class, args);
        TcpServer tcpServer = context.getBean(TcpServer.class);
        tcpServer.runServer();
        try {
            String serverAddr = "127.0.0.1:8848";
            String dataId = "xiaozhen-tcpserver-dev.yml";
            String group = "SYSTEM_GROUP";
            Properties properties = new Properties();
            properties.put("serverAddr", serverAddr);
            ConfigService configService = NacosFactory.createConfigService(properties);
            String content = configService.getConfig(dataId, group, 5000);
            System.out.println(content);
            configService.addListener(dataId, group, new Listener() {
                @SneakyThrows
                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("监听到配置文件变化");
                    //需要等待让其完成自动刷新配置
                    Thread.sleep(5000L);
                    tcpServer.closeServer();
                    tcpServer.runServer();
                }

                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
